<template>
  <div class="login">
    <div class="d_f j_c_s_b img a_i_c">
      <div class="d_f a_i_c">
        <img src="../assets/login_icon1.png" alt="" class="icon1">
        <img src="../assets/login_icon2.png" alt="" class="icon2">
      </div>
      <img src="../assets/login_icon3.png" alt="" class="icon3">
    </div>
    <div class="d_f j_c_s_b center">
      <div></div>
      <div class="box">
        <h3>欢迎登录：）</h3>
        <myform :fields="fields" :model="model" ref="ruleFrom" class="form" :rules="rules">
          <template v-slot:account>
            <div class="input d_f a_i_c">
              <el-input class="no-border" clearable v-model="model.account" placeholder="请输入账号" />
            </div>
          </template>
          <template v-slot:password>
            <div class="input d_f a_i_c">
              <el-input class="no-border" clearable v-model="model.password" show-password placeholder="请输入密码" />
            </div>
          </template>
          <template v-slot:code>
            <div class="d_f j_c_s_b w_100">
              <div class="code d_f a_i_c">
                <el-input class="no-border" @keyup.enter="login" clearable v-model="model.code" placeholder="请输入验证码" />
              </div>
              <SIdentify :identifyCode="identifyCode" @myEvent="myEvent"></SIdentify>
            </div>
          </template>
        </myform>
        <el-button class="w_100" type="primary" @click="login" :loading="loading">登 录</el-button>
      </div>
    </div>
  </div>
</template>

<script lang='ts'>
import { defineComponent, reactive, ref, toRefs, onBeforeMount } from 'vue'

import SIdentify from '@/components/Sidentify.vue'
import { dataType } from '../type/login'
import { useRouter } from 'vue-router'
import { Message } from '../utils/resetMessage'
import { grtLogin, empGetUserData, areaDatas } from '../api/login'
import md5 from "js-md5"
import { httpConfig } from '../utils/config'
import axios from 'axios'
import { useStore } from '../store/index';
export default defineComponent({
  name: '',
  components: {
    SIdentify
  },
  setup() {
    const data: dataType = reactive({
      fields: [
        {
          prop: 'account',
        },
        {
          prop: 'password',
        },
        {
          prop: 'code'
        }
      ],
      model: {
        account: '',
        password: '',
        //   account: '17311701405',
        // password: '701405',
        code: '',

      },
      identifyCode: '',
      sidentifyMode: '',
      identifyCodes: '1234567890abcdefjhijklinopqrsduvwxyz',
      rules: {
        account: [
          {
            required: true,
            message: '请输入账号',
            trigger: 'blur',
          },
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur',
          },
        ],
        // code: [
        //   {
        //     required: true,
        //     message: '请输入验证码',
        //     trigger: 'blur',
        //   },
        // ],
      },
      loading: false,
    })
    const router = useRouter()
    const ruleFrom = ref()
    const store = useStore();
    onBeforeMount(() => {
      localStorage.removeItem('myStore')
      localStorage.removeItem('Token')
      localStorage.removeItem('userVO')
      localStorage.removeItem('menuList')
      store.$reset()
      if (httpConfig.debug) {
        data.model.account = '17311701400'
        data.model.password = '123456'
      }


      makeCode(data.identifyCodes, 4)
      localStorage.removeItem('msgBox')
      window.history.pushState(null, '', window.location.href);
      // 清除完毕后，用一个新的记录替换当前的记录，这样用户不能通过后退回到清除前的页面
      window.history.replaceState(null, '', window.location.href);
    })
    // 生成随机数
    const randomNum = (min: number, max: number) => {
      max = max + 1
      return Math.floor(Math.random() * (max - min) + min)
    }
    // 随机生成验证码字符串
    const makeCode = (o: string, l: number) => {
      for (let i = 0; i < l; i++) {
        data.identifyCode += o[randomNum(0, o.length)]
      }
    }
    const getRandomString = (length: number) => {
      let result = '';
      const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      const charactersLength = characters.length;
      for (let i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
      }
      return result;
    }
    // 更新验证码
    const refreshCode = () => {
      data.identifyCode = ''
      makeCode(data.identifyCodes, 4)
    }
    const login = (): void => {
      ruleFrom.value.verification().then(() => {
        if (!httpConfig.debug) {
          if (data.model.code != data.identifyCode) {
            Message({ type: 'error', message: '验证码错误' })
            refreshCode()
            return
          }
        }
        data.loading = true
        let salt = 'KXY-9935'
        // let password = md5.hex_md5(data.model.password + salt) + getRandomString(10)
        let password = md5(data.model.password + salt) + getRandomString(10)
        grtLogin({ acctNo: data.model.account, password: password }).then((res: any) => {
          localStorage.setItem('Token', res)
          empGetUserData({}).then((ree: any) => {
            if (!localStorage.getItem('districts')) {
              getcityList()
            }
            localStorage.setItem('userVO', JSON.stringify(ree.userVO))
            if (ree.list.length == 0) {
              Message({ type: 'error', message: '当前账号暂无权限，请联系管理员' })
              data.loading = false
              return
            }
            store.setInfo(ree)
            data.loading = false
            Message({ type: 'success', message: '登录成功' })
            localStorage.setItem('menuList', JSON.stringify(ree.list))
            // router.push('/system/dictionary/index') 
          })
        }).catch(() => {
          data.loading = false
        })

      })
    }
    const filterArr = (data: any) => {
      data.map((item: any) => {
        if (item.districts.length > 0) {
          filterArr(item.districts)
        } else {
          delete item.districts
        }
      })
      data = data.filter((item: any) => {
        return item.adcode != '810000' && item.adcode != '710000' && item.adcode != '820000'
      })
      return data
    }
    const getcityList = () => {
      // areaDatas({}).then((res: any) => { 
      // })
      axios({
        url: httpConfig.mapUrl,
        method: 'get',
        params: {
          keywords: '',
          subdistrict: 3,
          extensions: 'base',
          key: httpConfig.mapKey
        }
      }).then((res: any) => {
        let districts = filterArr(res.data.districts[0].districts)
        districts.map(item => {
          if (item.adcode == '150000') {
            item.districts.map(item1 => {
              if (item1.adcode == '150100') {
                item1.districts.push({
                  adcode: "150126",
                  center:"111.623485,40.808906",
                  citycode:"0471",
                  level:"district",
                  name:"经济开发区",
                  districts:[],
                })
              }
            })
          }
        })
        localStorage.setItem('districts', JSON.stringify(districts))
      })
    }
    const myEvent = () => {
      refreshCode()
    }
    return {
      ...toRefs(data),
      makeCode,
      randomNum,
      login, ruleFrom,
      refreshCode,
      myEvent, filterArr, getcityList,
    }
  }
})
</script>
<style scoped lang='scss'>
.login {
  width: 100%;
  height: 100%;
  background-image: url('../assets/background.png');
  background-size: 100% 100%;

  .img {
    width: calc(100% - 12.5rem);
    margin-left: 6.25rem;
    padding-top: 4rem;

    .icon1 {
      height: 50px;
      width: 390px;
    }

    .icon2 {
      height: 35px;
      width: 300px;
      margin-left: 20px;
    }

    .icon3 {
      width: 194px;
      height: 31px;
    }
  }

  .center {
    margin-top: 6rem;
    width: 80%;
    margin-left: 10%;

  }

  .box {
    width: 340px;
    border-radius: 6px;

    background: linear-gradient(180deg, #FAFCFF 11%, #EDF2F9 100%);
    padding: 72px 46px;
  }

  .input {
    width: 100%;
    height: 40px;
    background: rgba(227, 229, 232, 0.6);
    border-radius: 3px;
  }

  .form {
    margin-top: 56px;
  }

  .code {
    width: 60%;
    height: 40px;
    background: rgba(227, 229, 232, 0.6);
    border-radius: 3px;
  }
}
</style>
<style lang='scss'>
.login {
  .el-form-item {
    width: 100%;
  }

  .el-input {
    width: 100% !important;
  }

  .el-input__wrapper {
    box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color)) inset;
    background: transparent !important;
    cursor: default;

    .el-input__inner {
      cursor: default !important;
    }
  }
}
</style>